package com.mew.sas.config;

import cn.hutool.core.util.StrUtil;
import com.mew.common.config.RedisConstantValue;
import com.mew.common.dc.db.LoginoutService;
import com.mew.common.enm.ExitType;
import com.mew.sas.service.OnlineGiftSasService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private LoginoutService loginoutService;
    @Autowired
    private OnlineGiftSasService onlineGiftSasService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }


    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        log.info("---KeyExpiration {} ---", expiredKey);
        if(expiredKey.startsWith(RedisConstantValue.SESSION_EXPIRE)){
            String[] str = StrUtil.split(expiredKey, ":");
            long userId = Long.parseLong(str[2]);
            loginoutService.logout(userId, ExitType.Expires.code());
            onlineGiftSasService.exit(userId, ExitType.Expires);
        }
    }
}
